# -*- coding: utf-8 -*-

from utils.dbbase import exc_sql
from datetime import datetime
from web.views.tools import md5hex
from web.views.base import set_cache, get_cache



def check_api_key(user_api_key, cop_id):
    redis_key = md5hex("user_secret_by_user_api_key"+user_api_key+cop_id)
    cache_data = get_cache(redis_key)
    if cache_data['errcode'] == 0:
        return cache_data['data']

    data = exc_sql(
        r"SELECT app_key, limit_time, app_secret FROM app_key WHERE cop_id = '{0}';".format(cop_id)
    )
    now_date = datetime.now()
    for _ in data:
        if user_api_key == _[0]:
            if now_date < _[1]:
                set_cache(redis_key,{
                    'errcode':0,
                    'api_secret':_[2]
                },24*60)
                return {
                    'errcode':0,
                    'api_secret':_[2]
                }
            else:
                return {
                    'errcode': 1,
                }
    return False




if __name__ == "__main__":
    check_api_key('2ac','2ac')
